package yto.freemarker.springbootnetty.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class NettyServer {
    public static void main(String[] args) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //接受新连接线程，主要负责创建新连接
        NioEventLoopGroup boos = new NioEventLoopGroup();
        //负责读取数据的线程，主要用于读取数据以及业务逻辑处理
        NioEventLoopGroup worker = new NioEventLoopGroup();
        serverBootstrap
                .group(boos, worker)
                //这里告诉Channel如何接收新的连接
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        //编码集
                        ch.pipeline().addLast(new StringDecoder());
                        //接收到请求后的数据的处理
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                System.out.println(msg);
                            }
                            /**
                             * 当Netty由于IO错误或者处理器在处理事件时抛出异常时调用
                             */
                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                // 当出现异常就关闭连接
                                cause.printStackTrace();
                                ctx.close();
//                                super.exceptionCaught(ctx, cause);
                            }
                        });
                    }
                })
                // 绑定端口，开始接收进来的连接
                .bind(8000);
    }
}
